<?php
namespace app\admin\controller;

use app\admin\controller\User;
use app\admin\model\Goods as G;
use \think\Db;
use \think\Cookie;
use app\api\controller\KbxOther;
use app\api\model\Fareharbor as F;
use app\api\controller\FareGoods as FApi;
use think\Exception;

class Faregoods extends User{

    //商品列表
    public function index(){
        $exportFlag=request()->param('exportFlag');//是否为导出

        $search_page = 20;
        //导出查询条件
        if($exportFlag==1){
            $search_page = 10000;
        }
        $where=[];
        if($this->request->isPost()){
            $post= request()->post();
            if (isset($post['item_id']) and $post['item_id'] > 0) {
                $where['item_id'] = $post['item_id'];
            }
            if (isset($post['search_name']) and $post['search_name'] !='') {
                $where['item_name|company']=['like','%'.$post['search_name'].'%'];
                $where['search_name']=$post['search_name'];
            }
            if (isset($post['company']) and $post['company'] !='') {
                $where['company']=['like','%'.$post['company'].'%'];
                $where['company']=$post['company'];
            }
            cache('wheres',$where);
        }else{
            $idss=$this->request->param('page');
            if(!empty($idss) || isset($exportFlag)){
                $where=cache('wheres');
            }else{
                cache('wheres',$where);
            }
        }
        $this->assign("where",$where);
        if(isset($where['search_name'])){
            unset($where['search_name']);
        }
        $list = db("fareharbor_goods")
            ->where($where)
            ->field('fare_goods_id,company,item_id,item_name,image_cdn_url,usd_price_section,`status`,is_update')
            ->order('fare_goods_id desc')->paginate($search_page);
        $data = [];
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $company = (new F())->getFareharborData();
        foreach($list as $key=>$value){
            $value['sell_section'] = '';
            if(!empty($value['usd_price_section'])){
                $value['sell_section'] = (new FApi())->getItemSellPrice($value['usd_price_section']);

                $section = explode("~",$value['usd_price_section']);
                $left = ceil($section[0]*$exchange['exchange_rate']*100)/100;
                $right = ceil($section[1]*$exchange['exchange_rate']*100)/100;
                $value['usd_price_section'] = $left.'~'.$right;
            }
            $value['company_name'] = 'unknown';
            foreach ($company as $k=>$v){
                if($v['shortname']==$value['company']){
                    $value['company_name'] = $v['name'];break;
                }
            }
            $data[] = $value;
        }

        $this->assign("company",$company);
        $this->assign("list",$list);
        $this->assign("data",$data);
        return $this->fetch();

    }
    //查看详情
    public function showgoodsdetail()
    {
        $get= request()->get();
        $id = isset($get['id'])?$get['id']:0;

        $info = db('fareharbor_goods')->find($id);
        if(empty($info)){
            return $this->error("您查询的商品不存在");
        }
        if(!empty($info['images'])){
            $info['images'] = json_decode($info['images'],true);
        }
        if(!empty($info['locations'])){
            $info['locations'] = json_decode($info['locations'],true);
        }
        if(!empty($info['customer_prototypes'])){
            $info['customer_prototypes'] = json_decode($info['customer_prototypes'],true);
            foreach ($info['customer_prototypes'] as $key=>$value){
                $info['customer_prototypes'] = (new FApi())->chNameByItemCustomer($info['customer_prototypes'],$info['item_id']);
            }
        }
        if(!empty($info['description_safe_html'])){
            $info['description_safe_html'] = htmlspecialchars_decode($info['description_safe_html']);
        }
        if(!empty($info['cancellation_policy_safe_html'])){
            $info['cancellation_policy_safe_html'] = htmlspecialchars_decode($info['cancellation_policy_safe_html']);
        }
        if(!empty($info['booking_notes'])){
            $info['booking_notes'] = htmlspecialchars_decode($info['booking_notes']);
        }
        $update_desc = [];
        if(!empty($info['update_desc'])){
            $desc_time = explode("##",$info['update_desc']);
            if(!empty($desc_time) && count($desc_time)>2){
                unset($desc_time[0]);
                foreach ($desc_time as $key=>$value){
                    $desc = explode('----',$value);
                    //数据更新在1条以上
                    if(count($desc) >1 && !empty($desc[1])){
                    foreach ($desc as $v){
                            if(!empty($v)) $update_desc[] = $v;
                        }
                    }
                }
            }else{
                $desc_time = isset($desc_time[1])?$desc_time[1]:$desc_time[0];
                $desc = explode('----',$desc_time);
                //数据更新在1条以上
                if(count($desc) >1 && !empty($desc[1])){
                foreach ($desc as $v){
                        if(!empty($v)) $update_desc[] = $v;
                    }
                }
            }
        }
        $this->assign('goods',$info);
        $this->assign('update_desc',$update_desc);
        return $this->fetch();

    }

    //添加商品
    public function addgoods(){
        $g=new G();
        //获取管理员id
        $adminid = Cookie::get('admin');

        if (request()->isPost()){
            $id = $this->request->has('goods_id') ? $this->request->param('goods_id', 0, 'intval') : 0;
            $gd=new Gdimg();
            if($id>0){//修改
                $date=request()->post();
                unset($date['goods_id']);
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['starttime', 'require', '开始时间不能为空'],
                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $date['starttime']=strtotime($date['starttime']);
                $date['endtime']=strtotime($date['endtime']);
                $date['updatetime']=time();
                $date['admin_id']=$adminid;
                $date['small_image']='';
                if (!empty($date['goods_image'])){
                    $image=!empty($date['goods_image'])?explode(',',$date['goods_image']):'';
                    if (!empty($image[1])){
                        $image= array_filter($image);
                        foreach ($image as $u){
                            $name=md5($u);
                            $url= $gd->compressImg($name,$u);
                            $date['small_image'].=$url.',';
                        }
                    }
                }

                $goodsname=$g->where("goods_name",$date['goods_name'])->where('goods_id','neq',$id)->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }

                //附属城市判断
                if(isset($date['belong_city']) && !empty($date['belong_city'])){
                    if($date['belong_city']!=999999){
                        $belong_city = explode(",",$date['belong_city']);
                        //将主要城市添加到附属城市中
                        if(!in_array($date['city_id'],$belong_city)){
                            array_unshift($belong_city,$date['city_id']);
                            $date['belong_city'] = implode(",",$belong_city);
                        }
                    }
                }else{
                    $date['belong_city'] = $date['city_id'];
                }


                Db::startTrans(); //启动事务
                try {
                    $g->allowField(true)->save($date, ['goods_id' => $id]);
                    Db::commit(); //提交事务
                    return $this->success('修改成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('修改失败');
                }
            }else{//新增
                $date=request()->post();

                unset($date['id']);

                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['goods_name', 'require', '商品不能为空'],
                    ['starttime', 'require', '开始时间不能为空'],
                    ['endtime', 'require', '结束不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($date)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                $date['goods_source']=1;
                $date['starttime']=strtotime($date['starttime']);
                $date['endtime']=strtotime($date['endtime']);
                $date['creattime']=time();
                $date['updatetime']=time();
                $date['admin_id']=$adminid;
                $date['small_image']='';
                if (!empty($date['goods_image'])){
                    $image=!empty($date['goods_image'])?explode(',',$date['goods_image']):'';
                    if (!empty($image[1])){
                        $image= array_filter($image);
                        foreach ($image as $u){
                            $name=md5($u);
                            $url= $gd->compressImg($name,$u);
                            $date['small_image'].=$url.',';
                        }
                    }
                }

                $goodsname=$g->where("goods_name",$date['goods_name'])->find();
                if($goodsname){
                    return $this->error('添加失败：商品名称已存在');
                }
                if( $date['starttime']>$date['endtime']){
                    return $this->error('添加失败：开始时间不能大于结束时间');
                }

                //附属城市判断
                if(isset($date['belong_city']) && !empty($date['belong_city'])){
                    if($date['belong_city']!=999999){
                        $belong_city = explode(",",$date['belong_city']);
                        //将主要城市添加到附属城市中
                        if(!in_array($date['city_id'],$belong_city)){
                            array_unshift($belong_city,$date['city_id']);
                            $date['belong_city'] = implode(",",$belong_city);
                        }
                    }
                }else{
                    $date['belong_city'] = $date['city_id'];
                }

                //判断是否为fareharbor商品
                if(!empty($date['fare_goods_id'])){
                    $date['channel_source'] = 'fareharbor';
                    $date['source_id'] = $date['fare_goods_id'];
                    //查看是否存在图片
                    $faregoodsinfo = db("fareharbor_goods")->find($date['fare_goods_id']);
                    $date['price_section'] = $faregoodsinfo['price_section'];
                    if(!empty($faregoodsinfo) && !empty($faregoodsinfo['images'])){
                        $images_arr = [];
                        $images = json_decode($faregoodsinfo['images'],true);
                        foreach ($images as $kk=>$vv){
                            $images_arr[] = $vv['image_cdn_url'];
                        }
                        if(!empty($images_arr)){
                            $goods_images = explode(",",$date['goods_image']);
                            $images_arr = array_merge($images_arr,$goods_images);
                            $date['goods_image'] = implode(",",$images_arr);
                        }
                    }
                }

                Db::startTrans(); //启动事务
                try {
                    $g->allowField(true)->save($date);
                    Db::commit(); //提交事务
                    return $this->success('添加成功');
                } catch (\PDOException $e) {
                    Db::rollback(); //回滚事务
                    return $this->error('添加失败');
                }
            }

        }else{
            //修改
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $goods=$g->where("goods_id",$id)->find();
            //获取tag
            $tag=$goods['tag_id'];
            $tag=explode(',',$tag);
            if($tag[0]){
                $tagdata=Array();
                foreach($tag as $key=>$value){
                    $tags=Db::name('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                    $tagdata[$key]=$tags;
                }

            }else{
                $tagdata='';
            }
            $this->assign('tagdata',$tagdata);

            //获取关联项目
            $relation=$goods['relation_type'];
            $goodscity=$goods['city_id'];
            $belong_city=$goods['belong_city'];
            $goodslocation=$goods['goods_location'];
            $goodsclassify=$goods['classify_id'];

            if ($relation=='1'){
                $da=  $g->trip($goodscity);
            }else if ($relation=='2'){
                $da=  $g->poi($goodscity,$goodsclassify);
            }else{
                $da='';
            }
            //获取轮播图
            $goodsimage=$goods['goods_image'];
            $goodsimage=explode(',',$goodsimage);
            $this->assign('goodsimage',$goodsimage);
            $this->assign('goods',$goods);
            $this->assign('relation',$da);
        }
        $city=$g->city();

        if($goodscity){
            $team=$g->team($goodscity,0);
        }else if ($city[0]['id']){
            $team=$g->team($city[0]['id'],0);
        }else{
            $team=[];
        }
        //附属城市
        $belongCityList = [];
        if(isset($belong_city) && !empty($belong_city)){
            if($belong_city!=999999){
                $belong_city = array_filter(explode(",",$belong_city));
                foreach ($city as $key => $value) {
                    if(in_array($value['id'],$belong_city)){
                        $belongCityList[] = $value;
                    }
                }
                $belong_city = implode(",",$belong_city);
            }
        }else{
            $belong_city = "";
        }

        $this->assign("belongcityid",$belong_city);
        $this->assign("belongCityList",$belongCityList);

        //关联项目
        $projectList = [];
        if(isset($goodslocation) && !empty($goodslocation)){
            $goodslocation = array_filter(explode(",",$goodslocation));
            foreach ($team as $key => $value) {
                if(in_array($value['id'],$goodslocation)){
                    $projectList[] = $value;
                }
            }
            $goodslocation = implode(",",$goodslocation);

        }else{
            $goodslocation = "";
        }
        $this->assign("goodslocation",$goodslocation);
        $this->assign("projectList",$projectList);

        //供应商
        list($supplier,$supplierNameArr) = (new Product())->getSupplierList();

        $this->assign('supplier',$supplier);


        //商品的订单类型
        $orderType = array(
            array('type'=>'Ticket_FIT','name'=>'地接社标品','orderFlag'=>0),
            array('type'=>'Ticket_POI','name'=>'门票类产品','orderFlag'=>0),
            array('type'=>'Hotel','name'=>'酒店','orderFlag'=>0),
            array('type'=>'Custom','name'=>'定制产品','orderFlag'=>1),
            array('type'=>'Vehicle','name'=>'用车','orderFlag'=>1),
            array('type'=>'Ticket_AIR','name'=>'机票','orderFlag'=>0),
            array('type'=>'Rental_Device','name'=>'物品购买/租赁','orderFlag'=>1),
            array('type'=>'Other','name'=>'其它','orderFlag'=>1),
            array('type'=>'Price_Gap','name'=>'补差价','orderFlag'=>1),
            array('type'=>'Self_Drive','name'=>'自驾游','orderFlag'=>1),
            array('type'=>'Personal_Tailor','name'=>'私人定制服务','orderFlag'=>1),
            array('type'=>'Subscription','name'=>'代订服务','orderFlag'=>1),
        );
        $this->assign('orderType',$orderType);

        //新增商品的标签
        $goodstags=Db::name('goodstag')->where(['tag_status'=>1])->field('tag_id,tag_name')->select();

        $companyList = (new F())->getFareharborData();
        $itemList = db("fareharbor_goods")->field("fare_goods_id,item_id,item_name,company")->order("fare_goods_id asc")->select();
        $this->assign('companyList',$companyList);
        $this->assign('itemList',$itemList);
        $this->assign('trip',$g->trip());
        $this->assign('tag',$g->tag());
        $this->assign('city',$city);
        $this->assign('team',$team);
        $this->assign('classify',$g->classify());
        $this->assign('thumb','');
        $this->assign('fileid',"");
        $this->assign('goodstags',$goodstags);
        return $this->fetch();
    }

    //获取fareharbor详情
    public function getFaregoosInfo()
    {
        $post = request()->post();
        if(empty($post)){
            return json(['code'=>-1,'msg'=>'获取数据失败']);
        }

        $id = $post['id'];
        $goodsinfo = db("fareharbor_goods")->find($id);
        if(!empty($goodsinfo)){
            return json(['code'=>200,'msg'=>'获取数据成功','data'=>$goodsinfo]);
        }else{
            return json(['code'=>-1,'msg'=>'获取数据失败']);
        }
    }
    //查看套餐
    public function showgoodsspec()
    {
        $get= request()->get();
        $id = isset($get['id'])?$get['id']:0;

        $info = db('fareharbor_goods')->find($id);
        if(empty($info)){
            return $this->error("您查询的商品不存在");
        }
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
        $cache =  (new FApi())->getItemSpecsList($info['company'],$info['item_id']);
        $tax = (new FApi())->getItemTaxPercentage($info['company'],$info['item_id']);
        $specname = db('faregoods_specname')->where('item_id',$info['item_id'])->select();
        $ename = [];//英文名称集合
        foreach ($cache as $key=>$value){
            $min_price = ceil($value['min_price']*(1+$tax/100)*100)/100;
            $cache[$key]['min_price'] = ceil($min_price*$exchange['exchange_rate']*$sell_rate['discount_num']*100)/100;
            $result = [];
            $goodsList = (new F())->getFareharborData([
                'company'=>$info['company'],
                'item'=>$info['item_id'],
                'date'=>$value['time']
            ]);
            $enNames = array_column($specname,'en_name');
            foreach ($goodsList as $k=>$v){
                $specs = $v['customer_type_rates'];
                $person = [];
                foreach ($specs as $kk=>$vv){
                    $display_name = $vv['customer_prototype']['display_name'];
                    if(array_search($display_name,$enNames)!==false){
                        $ch_name = $specname[array_search($display_name,$enNames)]['ch_name'];
                    }
                    $ch_name = empty($ch_name)?$display_name:$ch_name;
                    $usd_price = ceil($vv['customer_prototype']['total']*(1+$tax/100)*100)/100;
                    $person[] = [
                        'person_id'=>$vv['pk'],
                        'person_name'=>$vv['customer_prototype']['display_name'],
                        'person_cname'=>$ch_name,
                        'person_price'=>ceil($usd_price*$exchange['exchange_rate']*$sell_rate['discount_num']*100)/100,
                        'person_num'=>empty($vv['maximum_party_size'])?999:$vv['maximum_party_size'],
                        'minorder_num'=>empty($vv['minimum_party_size'])?1:$vv['minimum_party_size'],
                    ];
                }
                //套餐名称 由时间字段截取字符串获取 格式 2010-01-01T00:00:00-1000
                //获取日期 01
                $start_day = substr($v['start_at'],8,2);
                $end_day = substr($v['end_at'],8,2);
                //获取时间 00:00
                $start_time = substr($v['start_at'],11,5);
                $end_time = substr($v['end_at'],11,5);
                if($start_day==$end_day){
                    $specs_name = $start_time.'~'.$end_time;
                }else{
                    $specs_name = $start_day.'日'.$start_time.'~'.$end_day.'日'.$end_time;
                }

                $result[] = [
                    'specs_id'=>$value['pk'],
                    'specs_name'=>$specs_name,
                    'person'=>$person,
                    'gradeCode'=>''
                ];
            }
            $cache[$key]['specs'] = $result;
        }

        $this->assign('cache',$cache);
        return $this->fetch();

    }

    public function modifyfareupdstatus()
    {
        $post = request()->post();
        $id = $post['goods_id'];
        $goods = db("fareharbor_goods")->where("fare_goods_id",$id)->find();
        if(empty($goods)){
            return json(['code'=>-1,'msg'=>'商品不存在']);
        }else{
            db('fareharbor_goods')->where('fare_goods_id',$id)->update(['is_update'=>0,'update_time'=>time()]);
            return json(['code'=>200,'msg'=>'更新状态成功']);
        }
    }

    public function updfarechname()
    {
        $get =  request()->get();
        $post =  request()->post();

        if(empty($get['id'])) return $this->error('请选择商品');
        if(empty($post['cname'])) return $this->error('参数为空');
        $param =json_decode($post['cname'],true);
        db::startTrans();
        try{
            foreach ($param as $key=>$value){
                db('faregoods_specname')->where(['item_id'=>$get['id'],'en_name'=>$value['en_name']])->update(['ch_name'=>$value['ch_name']]);
            }
            db::commit();
            return json(['code'=>200,'msg'=>'修改成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'修改失败']);
        }
    }

}